import { _decorator, Component, Node, Prefab, instantiate, SystemEvent, Label } from "cc";
import { BaseComponent } from "../../core/component/BaseComponent";
const { ccclass, property } = _decorator;

@ccclass("TabMenu")
export class TabMenu extends BaseComponent {
    @property({ type: Prefab, displayName: "菜单项" })
    menuItemPrefab!: Prefab;

    @property({ type: Node, displayName: "菜单列表" })
    menuList!: Node;

    @property({ type: Boolean, displayName: "编辑器初始化" })
    editInit = true;

    menuItemTempNode!: Node;
    private currentSelectedIdx = -1;

    private selectedCallFunc!: Function;
    start() {
        if (!this.editInit) {
            this.menuItemTempNode = instantiate(this.menuItemPrefab) || this.menuList.children[0];
        }
    }

    initMenus(menuKeys: string[] | null, defaultSelectedIdx: number, callBackFunc: Function, target: Object) {
        if (!this.editInit && menuKeys) {
            menuKeys.forEach((menuKey: string, idx: number) => {
                let menuItemNode = this.menuList.children[idx];
                if (!menuItemNode) {
                    menuItemNode = instantiate(this.menuItemTempNode);
                    menuItemNode.parent = this.menuList;
                }
                menuItemNode.getChildByName("selected")!.getComponent(Label)!.string = menuKey;
                menuItemNode.getChildByName("normal")!.getComponent(Label)!.string = menuKey;
                menuItemNode.active = true;
            });
        }

        this.menuList.children.forEach((menuItemNode: Node, idx: number) => {
            menuItemNode.on(
                SystemEvent.EventType.TOUCH_END,
                () => {
                    this.onTouchEnd(idx);
                },
                this
            );
        });
        this.selectedCallFunc = callBackFunc.bind(target);
        this.onTouchEnd(defaultSelectedIdx);
    }

    private onTouchEnd(tabIdx: number) {
        if (this.currentSelectedIdx === tabIdx) {
            return;
        }
        this.currentSelectedIdx = tabIdx;
        this.menuList.children.forEach((child: Node, idx: number) => {
            if (idx === tabIdx) {
                child.getChildByName("selected")!.active = true;
                child.getChildByName("normal")!.active = false;
            } else {
                child.getChildByName("selected")!.active = false;
                child.getChildByName("normal")!.active = true;
            }
        });
        if (this.selectedCallFunc) {
            this.selectedCallFunc(tabIdx);
        }
    }

    // update (deltaTime: number) {
    //     // [4]
    // }
}
